from ui.components.base.widget import TgBaseWidget
from ui.components.containers.scroll_area import TgScrollArea
from ui.components.containers.layout import TgLayout
from .controllers.basis_monitor_controller import BasisMonitorController
from .views.basis_monitor_view import BasisMonitorView
from loguru import logger


class BasisMonitorTab(TgScrollArea):
    """基差监控 Tab"""

    def __init__(self):
        super().__init__()
        
        # 创建容器widget来放置布局
        container_widget = TgBaseWidget()
        layout = TgLayout(container_widget)
        self.setWidget(container_widget)
        
        # 创建MVC组件
        self.controller = BasisMonitorController()
        self.view = BasisMonitorView(layout, self)
        
        self._setup_mvc()
        # 不在初始化时启动自动刷新，改为在显示时启动


    def _setup_mvc(self):
        """连接MVC组件"""
        # 连接View与Controller
        self.controller.index_data_loaded.connect(self.view.update_index_table)
        self.controller.futures_data_loaded.connect(self.view.update_futures_table)
        self.controller.chart_data_ready.connect(self._on_show_chart)
        
        # 连接View的表格事件
        self.view.connect_table_signals(
            self._on_index_chart_requested,
            self._on_futures_chart_requested
        )


    def _on_index_chart_requested(self, row, column):
        symbol_code = self.view.get_index_table_cell_data(row, 0)
        if symbol_code:
            self.controller.show_index_chart(symbol_code)

    def _on_futures_chart_requested(self, row, column):
        symbol = self.view.get_futures_table_cell_data(row, 0)
        if symbol:
            self.controller.show_futures_chart(symbol)

    def _on_show_chart(self, chart_type: str, symbol: str):
        """处理图表显示请求"""
        if chart_type == "index":
            history_service = self.controller.model.get_stock_index_service()
        elif chart_type == "futures":
            history_service = self.controller.model.get_futures_history_service()
        else:
            return
        
        self.view.show_chart_dialog(chart_type, symbol, history_service)

    
    def cleanup(self):
        """清理资源"""
        self.controller.cleanup()

    def showEvent(self, event):
        # 当 Tab 可见时，启动定时刷新并立即刷新一次
        self.controller.start_auto_refresh()
        self.controller.refresh_data()
        super().showEvent(event)

    def hideEvent(self, event):
        # 当 Tab 隐藏时，停止定时刷新
        self.controller.stop_auto_refresh()
        super().hideEvent(event)